package edu.msse.signup.ui;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.EmailValidator;

import edu.msse.signup.domain.UserFactory;
import edu.msse.signup.domain.Users;
public class createUserHandler {
	private String name;
	private String username;
	private String password;
	private String phoneNumber;
	private String emailAddress;
	private UserFactory userFactory;
	private ApplicationService applicationService;
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getPhoneNumber() {
		return phoneNumber;
	}
	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}
	public String getEmailAddress() {
		return emailAddress;
	}
	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}
	
	public String submit(){
		Users user=null;
		try{
			if(!EmailValidator.getInstance().isValid(emailAddress)){
				applicationService.addErrorMessage("createUser:emailAddress","Email is invalid");
		        return null;
			}
			if(StringUtils.isBlank(emailAddress)){
				applicationService.addErrorMessage("createUser:emailAddress","Email is required.");
		        return null;
			}
			if(StringUtils.isBlank(password)){
				applicationService.addErrorMessage("createUser:password","Password is required.");
		        return null;
			}
			if(StringUtils.isBlank(phoneNumber)){
				applicationService.addErrorMessage("createUser:phoneNumber","Phone number is required.");
		        return null;
			}
			if(!StringUtils.isNumeric(phoneNumber)){
				applicationService.addErrorMessage("createUser:phoneNumber","Phone number is invalid. Enter only numbers, no dashes or spaces.");
		        return null;
			}
			if(StringUtils.isBlank(name)){
				applicationService.addErrorMessage("createUser:name","Name is required.");
		        return null;
			}
			
				
	           
			user=UserFactory.createUser(this.name, this.emailAddress, this.phoneNumber, this.password);
		}
		catch(Exception E)
		{
			   applicationService.addErrorMessage("createUser:general","User with same email exists.");
	           return null;
		}
		if (user==null)
			return "failure";
		else
			return "success";
	}
	public UserFactory getUserFactory() {
		return userFactory;
	}
	public void setUserFactory(UserFactory userFactory) {
		this.userFactory = userFactory;
	}
	public ApplicationService getApplicationService() {
		return applicationService;
	}
	public void setApplicationService(ApplicationService applicationService) {
		this.applicationService = applicationService;
	}

}
